package junior.util;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 基于{@link LinkedHashMap}实现的LRUCache
 * 
 * @author ZhangXiaoye
 *
 * @param <T>
 */
public class LRUCache<T> {
	
	private final LinkedHashMap<String, T> cache;
	
	public LRUCache(final int size){
		this.cache = new LinkedHashMap<String, T>(16, 0.75f, true){
			private static final long serialVersionUID = 3604253535493611328L;
			@Override
			protected boolean removeEldestEntry(Map.Entry<String,T> eldest) {
		        return size() > size;
		    }
		};
	}
	
	public T put(String key, T value){
		synchronized (cache) {
			return cache.put(key, value);
		}
	}
	
	public T get(String key){
		synchronized (cache) {
			return cache.get(key);
		}
	}
	
	public void clear(){
		synchronized (cache) {
			cache.clear();
		}
	}

	public int size(){
		synchronized (cache) {
			return cache.size();
		}
	}
}
